#include <stdio.h>
#include <unistd.h>//这是close，write接口的头文件
#include <string.h>
#include <fcntl.h>//这是 O_CREAT这些宏的头文件
#include <sys/stat.h>//umaska接口的头文件


int main()
{

  FILE* fp = fopen("./bite","wb+");
  if(fp==NULL)
  {
    perror("fopen error");
    return -1;
  }

  fseek(fp,0,SEEK_SET);

  char* data = "linux so easy!\n";

  //size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
  
  size_t ret = fwrite(data,1,strlen(data),fp);

  if(ret != strlen(data))
  {
    perror("fwrite error");
    return -1;
  }

  fseek(fp,0,SEEK_SET);//跳转读写位置到...,从文件起始位置开始偏移0个字节
  char buf[1024] = {0};

  //size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
  
  ret = fread(buf,1,1023,fp);
  //因为设置读取块大小位1，块个数为1023因此fread返回值为实际读取到的数据长度
  if(ret==0)
  {
    if(ferror(fp))//判断上一次IO是否正确
      printf("fread error");
    if(feof(fp))//判断是否读取到文件末尾
      printf("read end of file!\n");

    return -1;
  }

  printf("%s",buf);

  fclose(fp);









  ////将当前进程的默认文件创建权限掩码设置为0，并不影响系统的掩码，仅在当前进程有效
  //umask(0);
  ////int open(const char* pathname,int flags,mode_t mode)
  //int fd = open("./bite",O_CREAT | O_RDWR,0664);

  //if(fd<0)
  //{
  //  perror("open");
  //  return -1;
  //}

  //char* data = "i like linux!\n";
  ////ssize_t write(int fd,const void* buf,size_t count);
  //
  ////将data的数据写入到bite
  //ssize_t ret = write(fd,data,strlen(data));
  //if(ret<0)
  //{
  //  perror("write error");
  //  return -1;
  //}

  ////off_t lseek(int fd, off_t offset, int whence);
  //
  //lseek(fd,0,SEEK_SET);

  //char buf[1024] = {0};

  ////ssize_t read(int fd, void *buf, size_t count);
  //
  //ret = read(fd,buf,1023);

  //if(ret<0)
  //{
  //  perror("read error");
  //  return -1;
  //}
  //else if(ret==0)
  //{
  //  //应该是说明文件里面没有数据
  //  printf("end of file!\n");
  //  return -1;
  //}

  //printf("%s",buf);
  //close(fd);
  return 0;
}
